const xss = require('xss')
const Blog = require('../db/models/Blog')

const getList = async (author, keyword) => {

    // 动态拼接查询条件
    const whereOpt = {}
    if (author) whereOpt.author = author
    // 兼容模糊查询
    if (keyword) whereOpt.keyword = new RegExp(keyword)

    const list = await Blog.find(whereOpt).sort({ _id: -1 })

    return list
}

const getDetail = async (id) => {
    const blog = await Blog.findById(id)

    // 创建时间格式化

    return blog
}

const newBlog = async (blogData = {}) => {
    // blogData 是一个博客对象，包含 title content author属性

    const title = xss(blogData.title)
    const content = xss(blogData.content) 
    const author = blogData.author

    const blog = await Blog.create({
        title,
        content,
        author
    })

    return {
        id: blog._id
    }
}

const updateBlog = async (id, blogData = {}) => {
    // blogData 是一个博客对象，包含 title content 属性

    // 更新时只需要更新blogData的 title content 属性

    const title = xss(blogData.title)
    const content = xss(blogData.content)

    const blog = await Blog.findOneAndUpdate(
        { _id: id },
        { content, title },
        { new: true}
    )

    if (blog == null) return false
    return true
}

const deleteBlog = async (id, author) => {
    // id 就是要删除博客的id
    
    const blog = await Blog.findOneAndDelete({
        _id: id,
        author
    })
    if (blog == null) return false
    return true
}

module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    deleteBlog
}